package cn.bjit.interceptor;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.model.LoginUser;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JWTUtil;
import cn.bjit.util.JsonData;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal=new ThreadLocal<>();
    //在执行controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          //获取token，有2种可能 >1,header中携带，2，url中携带
        String accessToken = request.getHeader("token");
        if(accessToken==null){ //判断若果不是header中携带
            accessToken= request.getParameter("token"); //从url中获取
        }
         //如果不是空，则对token进行解密验证
        if(StringUtils.isNotBlank(accessToken)){

            Claims claims = JWTUtil.checkJWT(accessToken);
            if(claims==null){
                CommonUtil.sendJsonMessage(response, BizCodeEnum.ACCOUNT_UNLOGIN);
                return false;
            }
            long userId = Long.valueOf(claims.get("id").toString());
            String headImg = (String)claims.get("head_img");
            String name = (String)claims.get("name");
            String mail = (String)claims.get("mail");

            LoginUser  loginUser=new LoginUser();
            loginUser.setId(userId);
            loginUser.setName(name);
            loginUser.setHeadImg(headImg);
            loginUser.setMail(mail);
              //通过attritute传递用户信息
              //request.setAttribute("loginUser",loginUser);
              //通过threadLocal传递用户登录信息
            threadLocal.set(loginUser);
            return true;
        }
        //是空 就提示登录
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
